import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'dart:io';
import 'package:path/path.dart';
import '../models/note.dart';
import '../models/folder.dart';

/**
 * 本地存储服务
 * 负责数据的本地持久化存储
 */
class StorageService {
  static Database? _database;
  static SharedPreferences? _prefs;

  /**
   * 初始化存储服务
   */
  static Future<void> initialize() async {
    // 在桌面平台上初始化 sqflite_ffi
    if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
      sqfliteFfiInit();
      databaseFactory = databaseFactoryFfi;
    }
    
    _prefs = await SharedPreferences.getInstance();
    await _initDatabase();
  }

  /**
   * 初始化数据库
   */
  static Future<void> _initDatabase() async {
    final databasesPath = await getDatabasesPath();
    final path = join(databasesPath, 'linkbook.db');

    _database = await openDatabase(
      path,
      version: 1,
      onCreate: (db, version) async {
        // 创建文件夹表
        await db.execute('''
          CREATE TABLE folders (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            count INTEGER DEFAULT 0,
            is_default INTEGER DEFAULT 0,
            parent_id INTEGER,
            created_at TEXT,
            updated_at TEXT,
            is_shared INTEGER DEFAULT 0,
            share_link TEXT,
            sync_status TEXT
          )
        ''');

        // 创建笔记表
        await db.execute('''
          CREATE TABLE notes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            content TEXT NOT NULL,
            folder_id INTEGER NOT NULL,
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL,
            tags TEXT,
            sync_status TEXT,
            FOREIGN KEY (folder_id) REFERENCES folders (id)
          )
        ''');

        // 插入默认文件夹
        await db.insert('folders', {
          'id': 1,
          'name': '全部笔记',
          'is_default': 1,
          'created_at': DateTime.now().toIso8601String(),
          'updated_at': DateTime.now().toIso8601String(),
        });

        await db.insert('folders', {
          'id': 2,
          'name': '未分类笔记',
          'is_default': 1,
          'created_at': DateTime.now().toIso8601String(),
          'updated_at': DateTime.now().toIso8601String(),
        });
      },
    );
  }

  /**
   * 获取数据库实例
   */
  static Database get database {
    if (_database == null) {
      throw Exception('Database not initialized. Call StorageService.initialize() first.');
    }
    return _database!;
  }

  /**
   * 获取 SharedPreferences 实例
   */
  static SharedPreferences get prefs {
    if (_prefs == null) {
      throw Exception('SharedPreferences not initialized. Call StorageService.initialize() first.');
    }
    return _prefs!;
  }

  // ========== 笔记相关操作 ==========

  /**
   * 保存笔记
   */
  static Future<Note> saveNote(Note note) async {
    final db = database;
    
    final noteMap = {
      'title': note.title,
      'content': note.content,
      'folder_id': note.folderId,
      'created_at': note.createdAt.toIso8601String(),
      'updated_at': note.updatedAt.toIso8601String(),
      'tags': jsonEncode(note.tags),
      'sync_status': note.syncStatus,
    };

    if (note.id == 0) {
      // 新建笔记
      final id = await db.insert('notes', noteMap);
      return note.copyWith(id: id);
    } else {
      // 更新笔记
      await db.update(
        'notes',
        noteMap,
        where: 'id = ?',
        whereArgs: [note.id],
      );
      return note;
    }
  }

  /**
   * 获取所有笔记
   */
  static Future<List<Note>> getAllNotes() async {
    final db = database;
    final List<Map<String, dynamic>> maps = await db.query(
      'notes',
      orderBy: 'updated_at DESC',
    );

    return maps.map((map) => _noteFromMap(map)).toList();
  }

  /**
   * 根据ID获取笔记
   */
  static Future<Note?> getNoteById(int id) async {
    final db = database;
    final List<Map<String, dynamic>> maps = await db.query(
      'notes',
      where: 'id = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return _noteFromMap(maps.first);
    }
    return null;
  }

  /**
   * 删除笔记
   */
  static Future<void> deleteNote(int id) async {
    final db = database;
    await db.delete(
      'notes',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  /**
   * 根据文件夹ID获取笔记
   */
  static Future<List<Note>> getNotesByFolderId(int folderId) async {
    final db = database;
    final List<Map<String, dynamic>> maps = await db.query(
      'notes',
      where: 'folder_id = ?',
      whereArgs: [folderId],
      orderBy: 'updated_at DESC',
    );

    return maps.map((map) => _noteFromMap(map)).toList();
  }

  // ========== 文件夹相关操作 ==========

  /**
   * 保存文件夹
   */
  static Future<Folder> saveFolder(Folder folder) async {
    final db = database;
    
    final folderMap = {
      'name': folder.name,
      'count': folder.count,
      'is_default': folder.isDefault ? 1 : 0,
      'parent_id': folder.parentId,
      'created_at': folder.createdAt?.toIso8601String(),
      'updated_at': folder.updatedAt?.toIso8601String(),
      'is_shared': folder.isShared == true ? 1 : 0,
      'share_link': folder.shareLink,
      'sync_status': folder.syncStatus,
    };

    if (folder.id == 0) {
      // 新建文件夹
      final id = await db.insert('folders', folderMap);
      return folder.copyWith(id: id);
    } else {
      // 更新文件夹
      await db.update(
        'folders',
        folderMap,
        where: 'id = ?',
        whereArgs: [folder.id],
      );
      return folder;
    }
  }

  /**
   * 获取所有文件夹
   */
  static Future<List<Folder>> getAllFolders() async {
    final db = database;
    final List<Map<String, dynamic>> maps = await db.query(
      'folders',
      orderBy: 'is_default DESC, created_at ASC',
    );

    return maps.map((map) => _folderFromMap(map)).toList();
  }

  /**
   * 删除文件夹
   */
  static Future<void> deleteFolder(int id) async {
    final db = database;
    
    // 检查是否为默认文件夹
    final folder = await db.query(
      'folders',
      where: 'id = ? AND is_default = 0',
      whereArgs: [id],
    );
    
    if (folder.isNotEmpty) {
      // 将该文件夹下的笔记移动到"未分类笔记"
      await db.update(
        'notes',
        {'folder_id': 2},
        where: 'folder_id = ?',
        whereArgs: [id],
      );
      
      // 删除文件夹
      await db.delete(
        'folders',
        where: 'id = ?',
        whereArgs: [id],
      );
    }
  }

  // ========== 设置相关操作 ==========

  /**
   * 保存设置
   */
  static Future<void> saveSetting(String key, dynamic value) async {
    if (value is String) {
      await prefs.setString(key, value);
    } else if (value is int) {
      await prefs.setInt(key, value);
    } else if (value is double) {
      await prefs.setDouble(key, value);
    } else if (value is bool) {
      await prefs.setBool(key, value);
    } else if (value is List<String>) {
      await prefs.setStringList(key, value);
    } else {
      await prefs.setString(key, jsonEncode(value));
    }
  }

  /**
   * 获取设置
   */
  static T? getSetting<T>(String key, [T? defaultValue]) {
    if (T == String) {
      return prefs.getString(key) as T? ?? defaultValue;
    } else if (T == int) {
      return prefs.getInt(key) as T? ?? defaultValue;
    } else if (T == double) {
      return prefs.getDouble(key) as T? ?? defaultValue;
    } else if (T == bool) {
      return prefs.getBool(key) as T? ?? defaultValue;
    } else {
      final jsonStr = prefs.getString(key);
      if (jsonStr != null) {
        return jsonDecode(jsonStr) as T;
      }
      return defaultValue;
    }
  }

  /**
   * 清除所有数据
   */
  static Future<void> clearAllData() async {
    final db = database;
    
    // 清除笔记
    await db.delete('notes');
    
    // 清除非默认文件夹
    await db.delete('folders', where: 'is_default = 0');
    
    // 重置默认文件夹的计数
    await db.update(
      'folders',
      {'count': 0},
      where: 'is_default = 1',
    );
    
    // 清除设置
    await prefs.clear();
  }

  // ========== 辅助方法 ==========

  /**
   * 从数据库映射创建 Note 对象
   */
  static Note _noteFromMap(Map<String, dynamic> map) {
    return Note(
      id: map['id'],
      title: map['title'],
      content: map['content'],
      folderId: map['folder_id'],
      createdAt: DateTime.parse(map['created_at']),
      updatedAt: DateTime.parse(map['updated_at']),
      tags: map['tags'] != null ? List<String>.from(jsonDecode(map['tags'])) : [],
      syncStatus: map['sync_status'],
    );
  }

  /**
   * 从数据库映射创建 Folder 对象
   */
  static Folder _folderFromMap(Map<String, dynamic> map) {
    return Folder(
      id: map['id'],
      name: map['name'],
      count: map['count'] ?? 0,
      isDefault: map['is_default'] == 1,
      parentId: map['parent_id'],
      createdAt: map['created_at'] != null ? DateTime.parse(map['created_at']) : null,
      updatedAt: map['updated_at'] != null ? DateTime.parse(map['updated_at']) : null,
      isShared: map['is_shared'] == 1,
      shareLink: map['share_link'],
      syncStatus: map['sync_status'],
    );
  }
}